#include <stdlib.h>
#include <stdio.h>
#include "crvm.h"

bpList * bp_list_alloc(void)
{
		bpList *list;
		list = (bpList*) malloc(sizeof(bpList));
		if(!list)
		{
				printf("not enoughf memory to alloc\n");
				exit(1);
		}
		return list;
}

void bp_list_free(bpList* bp)
{
		if(bp != NULL)
				free(bp);
}

bpList* bp_list_prepend(bpList *list, word data,uint count)
{
		bpList *new_list;
		new_list = bp_list_alloc();
		new_list->data = data;
		new_list->count = count;
		new_list->next = list;
	
		return new_list;
}

bpList* bp_list_find(bpList* list,word data)
{
		while(list)
		{
				if(list->data == data)
						break;
				list = list->next;
		}
		
		return list;
}

bpList* bp_list_remove(bpList* list,word data)
{
		bpList *prev;
		bpList *tmp;
		tmp = list;
		prev = NULL;
		while(tmp)
		{
				if(tmp->data == data)
				{
						if(prev)
						{
								prev->next = tmp->next;
								bp_list_free(tmp);
						}
						if(list == tmp)
								list = list->next;
						break;

				}
			prev = tmp;
		tmp = tmp->next;	
		}
		return list;
}

bpList* bp_list_remove_nth(bpList* list,int nth)
{
		bpList *prev;
		bpList *tmp;
		tmp = list;
		prev = NULL;
		while(tmp)
		{
				if(nth-- == 0)
				{
						if(prev)
						{
								prev->next = tmp->next;
								bp_list_free(tmp);
						}
						if(list == tmp)
								list = list->next;
						break;

				}
			prev = tmp;
		tmp = tmp->next;	
		}
		return list;
}

bpList *bp_list_remove_all(bpList *list)
{
	bpList *tmp;
	tmp = list;
	while(list)
	{
		list = list->next;
		bp_list_free(tmp);
		tmp = list;
	}
	list = NULL;
	return list;
}



bool bp_list_check(bpList *list,word address)
{
	bpList *tmp;
	bool result = 0;
	if(tmp = bp_list_find(list,address))
	{
		if(!tmp->disable)
		{
			result = 1;
			if(tmp->count != 0)	
			{
				if(tmp->count-- ==0)
					tmp->disable = 1;
			}
		}

	}

	return result;

}